package _2工具类;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

public class WordDAOImpl implements IWordDAO {

	Connection conn;
	Statement stmt;

	public void getconnection() throws SQLException {
		// 1. 获取连接
		conn = DbUtils.getConnection();
		// 2. 查询对象
		stmt = conn.createStatement();
	}

	@Override
	public int insert(Word w) throws SQLException {
		// TODO Auto-generated method stub
		getconnection();
		// 3. 执行查询
		String sql = "insert into word(wordname,userid) value('" + w.getWordname() + "','" + w.getUserid() + "')";
		int result = stmt.executeUpdate(sql);
		// 4. 释放资源
		DbUtils.destoryResource(conn, stmt, null);
		return result;
	}

	@Override
	public int deleteById(int wordid, int userid) throws SQLException {
		// TODO Auto-generated method stub
		getconnection();
		// 3. 执行查询
		String sql = "delete from word where wordid='" + wordid + "'" + "and userid=" + userid;
		int result = stmt.executeUpdate(sql);
		// 4. 释放资源
		DbUtils.destoryResource(conn, stmt, null);
		return result;
	}

	@Override
	public int update(Word w) throws SQLException {
		// TODO Auto-generated method stub
		getconnection();
		// 3. 执行查询
		String sql = "update word set wordname='" + w.getWordname() + "'" + " where wordid='" + w.getWordid() + "'"
				+ "and userid=" + w.getUserid();
		int result = stmt.executeUpdate(sql);
		// 4. 释放资源
		DbUtils.destoryResource(conn, stmt, null);
		return result;
	}

	@Override
	public List<Word> findById(int userid) throws SQLException {
		// TODO Auto-generated method stub
		List<Word> result = new ArrayList<>();
		getconnection();
		// 3. 执行查询
		String sql = "select * from word where userid=" + userid;
		ResultSet rs = stmt.executeQuery(sql);
		while (rs.next()) {
			int id = rs.getInt(1);
			String wordname = rs.getString(2);
			int uid = rs.getInt(3);
			Word w = new Word(id, wordname, uid);
			result.add(w);
		}
		// 4. 释放资源
		DbUtils.destoryResource(conn, stmt, rs);
		return result;
	}

	@Override
	public List<Word> findAll() throws SQLException {
		// TODO Auto-generated method stub
		return null;
	}

}
